<template>
  <div class="app-main-content">
    <searchbar ref="searchbar" :searchItems="searchItems" :pagination="pagination"
               @resizeSearchbar="resizeSearchbar" @search="getDataList" class="grid-search-bar"></searchbar>
    <!--<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">-->
      <!--<el-form-item>-->
        <!--<el-input v-model="dataForm.vecNo" placeholder="车牌号" clearable></el-input>-->
      <!--</el-form-item>-->
      <!--<el-form-item>-->
        <!--<el-button @click="getDataList()"  size="small" >查询</el-button>-->
          <!--<el-button type="success" icon="el-icon-document" size="small" @click="exportRep">-->
            <!--导出数据-->
          <!--</el-button>-->
      <!--</el-form-item>-->
    <!--</el-form>-->
    <el-table
      :data="dataList"
      border
      :max-height="tableHeight"
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        prop="catNmCn"
        label="报警类型"
      >
      </el-table-column>
      <el-table-column
        prop="entpName"
        label="运输企业"
      >
      </el-table-column>
      <el-table-column
        prop="vecNo"
        label="车牌号"
      >
      </el-table-column>


      <el-table-column
        prop="driverName"
        label="驾驶员"
      >
      </el-table-column>
      <el-table-column
        prop="alarmValue"
        label="报警值"
      >
      </el-table-column>
      <el-table-column
        prop="threshold"
        label="报警阀值"
      >
      </el-table-column>


      <el-table-column
        prop="alarmTime"
        label="报警时间"
      >
      </el-table-column>


      <el-table-column
        prop="isHandle"
        label="处理状态"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isHandle ===0"
                  close-transition
                  :type="'primary'"  >
            未处理
          </el-tag>
          <el-tag v-if="scope.row.isHandle === 1"
                  close-transition
                  :type="'success'"  >
            已处理
          </el-tag>
          <el-tag v-if="scope.row.isHandle === 2"
                  close-transition
                  :type="'warning'">
            填报错误
          </el-tag>
        </template>
      </el-table-column>


      <el-table-column
        prop="location"
        header-align="center"
        align="center"
        label="报警位置">
        <template slot-scope="scope">
          <el-button @click="showAlarmLoc(scope.row)" type="text">查看报警位置</el-button>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isHandle == 0" size="mini" type="primary" @click="handleAlarm(scope.row)">处理</el-button>
          <!--<el-button type="text" size="small" @click="deleteHandle(scope.row.id)">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-button-group>
      <el-button type="success" icon="el-icon-document" size="small" @click="exportRep">
        导出数据
      </el-button>
    </el-button-group>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :page-sizes="[20, 30, 50, 100, 200]" style="float:right;"
      :page-size="pagination.limit" :current-page.sync="pagination.page" :total="pagination.total"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <map-dialog    v-if="dialogVisible" ref="mapDialog" :childComp="'showRoads'" :data-source="datas"  :title="'查看报警位置'" style="   margin-top:5vh;">
      <show-loc :data-source="datas"></show-loc>
    </map-dialog>
  </div>
</template>


<script>
  import * as $http from '@/api/alarm'
  import * as Tool from "@/utils/tool";
  import mapDialog from './map-dialog'
  import Searchbar from '@/components/Searchbar'
  import showLoc from './show-loc'
  export default {
    data() {
      return {
        dataForm: {
          vecNo: ''
        },
        dialogVisible:false,
        tableHeight: Tool.getClientHeight()-210,
        dataList: [],

        searchItems:{
          normal: [
            { name:'报警类型', field:'catNmCn', type:'radio',
              options:[
                //1:怠速行驶,2表示超速,3表示疲劳驾驶，4表示违停
                { label: "全部违章", value: "" },
                { label: "超速报警", value: "超速报警" },
                { label: "停车报警", value: "停车报警" },
                { label: "疲劳驾驶", value: "疲劳驾驶" },
                { label: "异常开锁", value: "异常开锁" }
              ],
              dbfield:'cat_nm_cn',dboper:'eq',default:""
            },
            { name:'车牌号', field:'vecNo', type:'text',dbfield:'vec_no',dboper:'cn'},
            { name:'违章时间', field:'alarmTime ', type:'daterange',dbfield:'alarm_time',dboper:'bt',valueFormat:'yyyy-MM-dd HH:mm:ss'}
          ],
          more: [
            { name:'处理类型', field:'isHandle', type:'select', postdifferent:true,
              options: [
                { label: "全部处理类型", value: "", dboper:"eq", postData:""},
                { label: "已受理", value: "0", dboper:"eq", postData:"0"},
                { label: "已处理", value: "1", dboper:"eq", postData:"1"},
                { label: "填报错误", value: "2", dboper:"eq", postData:"2"},
              ],
              dbfield:'is_handle',dboper:'eq'
            }
          ]
        },
        pagination: {
          page: 1,
          limit: 15,
          total: 0
        },
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      Searchbar,
      mapDialog,
      showLoc
    },
    mounted: function () {
      window.addEventListener('resize', this.setTableHeight);
      this.setTableHeight();
      this.getDataList()
    },

    methods: {

      setTableHeight(){
        this.$nextTick(() => {
          this.tableHeight = Tool.getClientHeight() - 160 - this.$refs.searchbar.$el.offsetHeight;
        });
      },
      // 改变搜索框的高度
      resizeSearchbar() {
        this.setTableHeight();
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true
        let filters =    this.$refs.searchbar.get();
        let param = Object.assign({filters:filters},this.pagination);
        $http.list(param).then(data => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 删除
      deleteHandle(id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.ipPk
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText:
            '取消',
          type:
            'warning'
        }).then(() => {
          $http.del(ids).then(data => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      //查看报警位置
      showAlarmLoc(row){
        this.datas = {lat:row.alarmLatitude,lng:row.alarmLongitude,location:row.location};
        if(this.$refs['mapDialog'] && this.$refs['mapDialog'].showMap)
          this.$refs['mapDialog'].showMap();
        else
        if(!this.dialogVisible)
          this.dialogVisible = true;
      },
      //处理违章报警
      handleAlarm(row){

        let params = {
          id:row.id,
          status:1,
          handlePerson:this.$store.state.user.username,
          handleRemark:""
        };
        this.$prompt('请输入处理意见', '处理违章报警', {
          confirmButtonText: '确定',
          cancelButtonText:
            '取消',
          type:
            'warning'
        }).then(({ value }) => {
          params.handleRemark = value;
          $http.handleAlarmApi(params).then( res => {
            if(res.code == 0){
              this.$message.success('处理成功！');
              this.getDataList();
            }else{
              this.$message.error(res.msg || '处理失败！');
            }
          })
            .catch( err => {
              console.log(err);
            });
        })      .catch( err => {
          console.log(err);
        });
      },
      //导出数据
      exportRep(){
        $http.exportExcel().then( res => {
          let a = document.createElement('a');
          let blob = new Blob([res]);
          let url = window.URL.createObjectURL(blob);
          let D = new Date();
          let _date = D.getFullYear()+'-'+(D.getMonth()+1)+'-'+D.getDate();

          a.href = url;
          a.download = '违章报警汇总统计_'+_date+'.xlsx';
          a.click();
          window.URL.revokeObjectURL(url);
        })
          .catch( err => {
            console.log(err);
          });
      }
    }
  }
</script>
